package com.elock.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.dao.impl.DaoCenter;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.WebUtils;

/**
 * Dao - 终端实时位置信息
 * @author 仁德
 */
@Repository("terminalRealtimePositionDao")
public class TerminalRealtimePositionDao extends DaoCenter {

	public Page<Map<String, Object>> findPage(String ids, Pageable pageable) {

		StringBuilder sql = new StringBuilder();
		sql.append(
				"select r.*,o.is_online,o.online_time from terminal_online o,terminal_realtime_position r");
		sql.append(
				" where o.terminal_id=r.terminal_id and r.terminal_id in (" + ids + ")");
		Page<Map<String, Object>> page = getNativeDao().findPageMap(sql.toString(),
				null,
				pageable);

		return page;
	}

	public List<Map<String, Object>> findList(String ids, Date terminalDate) {

		StringBuilder sql = new StringBuilder();
		sql.append(
				"select r.*,o.is_online,o.online_time,o.modify_date on_off_date,t.sim from terminal_online o,terminal_realtime_position r,terminal t");
		sql.append(
				" where o.terminal_id=r.terminal_id and t.id=o.terminal_id and r.terminal_id in ("
						+ ids
						+ ")");
		Object[] objs = null;
		if (terminalDate != null) {
			sql.append(" and (r.modify_date > ? or o.modify_date > ?)");
			objs = new Object[] { terminalDate, terminalDate };
		}
		sql.append(" order by r.modify_date desc");
		List<Map<String, Object>> list = getNativeDao().findListMap(sql.toString(),
				objs,
				0);

		return list;
	}

	public List<Map<String, Object>> findPointsList(String terminalNum, String startTime,
			String endTime) {

		List<Object> list = new ArrayList<Object>();
		StringBuilder sql = new StringBuilder();
		Long companyInfoId = WebUtils.getCurrentCompanyInfoId();
		sql.append("select t.latitude, t.longitude, t.gps_time from terminal_position t");
		sql.append(" where ifnull(t.latitude,0) <> 0 and ifnull(t.longitude,0) <> 0");
		sql.append(" and t.terminal_num = ?");
		list.add(terminalNum);
		if (companyInfoId != null) {
			sql.append(" and t.company_info_id=?");
			list.add(companyInfoId);
		}
		if (!ConvertUtil.isEmpty(startTime)) {
			sql.append(" and t.gps_time > ?");
			list.add(startTime);
		}
		if (!ConvertUtil.isEmpty(endTime)) {
			sql.append(" and t.gps_time <= ?");
			list.add(endTime);
		}
		sql.append(" order by t.gps_time");

		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}
		List<Map<String, Object>> points = getNativeDao().findListMap(sql.toString(),
				objs,
				3500);

		return points;
	}
}